//
//  NCLocationController.m
//  IPhoneDemo
//
//  Created by Neusoft on 11-7-13.
//  Copyright 2011 Neusoft. All rights reserved.
//

#import "NCLocationController.h"

#define CS_Location_OK              @"1"
#define CS_Location_Error           @"0"

@implementation NCLocationController

@synthesize delegate = _delegate;
@synthesize locMgr = _locMgr;
@synthesize sid, sname;

+ (BOOL)isLocationEnabled
{
    return ([CLLocationManager locationServicesEnabled]
            && [CLLocationManager authorizationStatus] != kCLAuthorizationStatusDenied);
}

#pragma mark -
#pragma mark Override base funcitons
- (id)init {
	self = [super init];
	
	if(self != nil) {
		_locMgr = [[CLLocationManager alloc] init];
        _locMgr.distanceFilter = 1000;
		_locMgr.delegate = self;
        sid     = [[NSString alloc] init];
        sname   = [[NSString alloc] init];
	}
	
	return self;
}

- (void)dealloc {
    [sid release];
    [sname release];
	[_locMgr release];
	[super dealloc];
}

- (void)sendLocationFinishedMsg:(id)result
{
    [[NSNotificationCenter defaultCenter] postNotificationName:CS_LocationFinished_Msg
                                                        object:result];
}

#pragma mark -
#pragma mark NCLocationController delegate functons
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation {
    
    [_locMgr stopUpdatingLocation];

    // If spend too long time,the data maybe with problems
    NSTimeInterval howRecent = [newLocation.timestamp timeIntervalSinceNow];
    if (howRecent < -10){
        [self sendLocationFinishedMsg:CS_Location_Error];
        return;
    }
    
	if([self.delegate respondsToSelector:@selector(locationUpdate:)])
    {
		[self.delegate locationUpdate:newLocation];
	}
    
    [self sendLocationFinishedMsg:CS_Location_OK]; 
}

- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error {
    
    [_locMgr stopUpdatingLocation];
    
    [self sendLocationFinishedMsg:CS_Location_Error];
    
	if([self.delegate conformsToProtocol:@protocol(NCLocationControllerDelegate)]) {
		[self.delegate locationError:error];
	}
}

#pragma mark -
#pragma mark Public functons
- (void)startUpdatingLocation
{
    if(![NCLocationController isLocationEnabled])
    {
        //no
        [self sendLocationFinishedMsg:CS_Location_Error];
        
        if([self.delegate conformsToProtocol:@protocol(NCLocationControllerDelegate)]) {
            [self.delegate locationError:nil];
        }
        return;
    }
	[_locMgr startUpdatingLocation];
}


@end
